{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# images and heatmaps"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We are going to use a digital elevation model (DEM) from the [basemap tutorial](https://github.com/rveciana/BasemapTutorial/blob/master/code_examples/sample_files/dem.tiff) as the sample data set in this section (which is bunlded in the repository as an npy file) for the zone of Montserrat at 5m resolution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "im = np.load('data/dem.npy')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(f\"type: {type(im)}, shape: {im.shape}, dtype: {im.dtype}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To display 2D images the data needs to be spatially re-sampled to fit the screen and mapped from scaler values in the array to the colors we see on the screen."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.imshow(im)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "of course we should include a color bar to go with the image:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "img = ax.imshow(im)\n",
    "cbar = fig.colorbar(img)\n",
    "cbar.set_label('elevation')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By default the colors are scaled over the full range of the input data, however this may not always be what you want (for example, if you are interested on a small contrast on top of a background or if there are extreme outliers).  To set the lower limit, use the `vmin` parameter to `imshow`  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "img = ax.imshow(im, vmin=700)\n",
    "cbar = fig.colorbar(img)\n",
    "cbar.set_label('elevation')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note how the upper left which used to have texture is now colored unifromly and the lower limit of the color bar has been changed."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise\n",
    "\n",
    "Use the `vmax` parameter to restrict color space from above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## All the colors\n",
    "\n",
    "While the default color map, [which replace 'jet' in mpl 2.0](https://bids.github.io/colormap/) has many good properties, but sometimes you just are not feeling the green (or have a [domain specfic reason for needing a different color map](https://matplotlib.org/cmocean)).  The color map can be controlled via the `cmap` parameter to `imshow`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "img = ax.imshow(im, cmap='magma')\n",
    "cbar = fig.colorbar(img)\n",
    "cbar.set_label('elevation')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise\n",
    "\n",
    "Have a look at the [color maps available](https://matplotlib.org/tutorials/colors/colormaps.html) and try out some different colors."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Follow the lines\n",
    "\n",
    "A different way to visualize array data is via a contour plot."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)\n",
    "ax1.contour(im, cmap='magma')\n",
    "ax1.set_aspect('equal')\n",
    "ax2.imshow(im, cmap='magma', origin='lower')      # put (0, 0) on the lower left to match contour"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise\n",
    "\n",
    "Try changing the `cmap` and `levels` parameters to `contour`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Change the normalization\n",
    "\n",
    "The conversion of your input data to the image on the screen is a multi-step process:\n",
    "\n",
    " - Your data is mapped to the range [0, 1] via a `Normalization`\n",
    " - The renormalized data is re-sampled to the correct number of pixels to fit on your output\n",
    " - The resampled data is mapped from [0, 1] -> RGB via the color map\n",
    " \n",
    "The default normalization in linear, however there are cases where you need a more exotic normalization.\n",
    "\n",
    "One such case is if your data covers several orders of magnitude."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from matplotlib.colors import LogNorm\n",
    "\n",
    "# take the 2D fft of our test image and re-order to put 0 frequency in the center\n",
    "spike = np.abs(np.fft.fftshift(np.fft.fft2(im)))\n",
    "\n",
    "fig, (ax1, ax2) = plt.subplots(1, 2, tight_layout=True, figsize=(10, 5))\n",
    "\n",
    "lin_im = ax1.imshow(spike)\n",
    "_ = fig.colorbar(lin_im, ax=ax1)\n",
    "_ = ax1.set_title('linear color scale')\n",
    "\n",
    "log_im = ax2.imshow(spike, norm=LogNorm())\n",
    "_ = fig.colorbar(log_im, ax=ax2)\n",
    "_ = ax2.set_title('log color scale')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can make use of a `BoundryNorm` to quantize the data (in in possibly non-uniform bins)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.colors as mcolors\n",
    "import matplotlib.cm as mcm\n",
    "\n",
    "cmap = mcm.tab20b\n",
    "norm = mcolors.BoundaryNorm([1, 3, 4, 5, 7, 9, 12, 15, 20], cmap.N)\n",
    "\n",
    "data = np.arange(20).reshape((1, 20))\n",
    "\n",
    "fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 6))\n",
    "\n",
    "top = ax1.imshow(data, cmap=cmap, aspect='auto')\n",
    "fig.colorbar(top, ax=ax1)\n",
    "bottom = ax2.imshow(data, norm=norm, cmap=cmap, aspect='auto')\n",
    "fig.colorbar(bottom, ax=ax2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
